package com.njitzx.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    //将密钥 和数据加密生产token

    //创建token 传入三个参数  密钥  过期时间
    public static String createJWT(String secretKey, long ttlMills, Map<String, Object> claims) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long expMills = System.currentTimeMillis() + ttlMills;
        Date exp = new Date(expMills); //long转为Date
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)  //载荷
                .signWith(signatureAlgorithm, secretKey.getBytes(StandardCharsets.UTF_8))
                .setExpiration(exp); //过期时间
        return builder.compact(); // 变为字符串
    }

    /*
    根据token解析得到里面的数据
     */
    public static Claims parseJWT(String secretKey, String token) {
       try {
           Claims claims = Jwts.parser().setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                   .parseClaimsJws(token).getBody();
           return claims;
       }catch (Exception e){
           throw new RuntimeException("token失效");
       }
    }
}
